package com.shushan.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.RelativeLayout;

import com.android.common.ui.UnScrollGrideView;
import com.android.common.ui.banner.Banner;
import com.android.common.ui.banner.BannerConfig;
import com.android.common.ui.banner.listener.OnBannerListener;
import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.andview.refreshview.XRefreshView;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBookDao;
import com.shushan.home.adapter.RecommendLessonsAdapter;
import com.shushan.home.adapter.WhiteAppsAdapter;
import com.shushan.home.bean.BannerDataBean;
import com.shushan.home.bean.IndexBean;
import com.shushan.home.bean.LearnByDoBean;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.mixedexam.OralCalculateExamActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.pages.SpecialTopicVideoActivity;
import com.shushan.pages.bean.SubjectSyncExerciseBean;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.ForegroundRTAService;
import com.shushan.setting.ParentSettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.exercise.SyncExerciseActivity;
import com.shushan.mixedexam.OralCalculateExerciseActivity;
import com.shushan.pages.NewStudyWithExerciseActivity;
import com.shushan.pages.newtype.EnglishWordsExerciseActivity;
import com.shushan.pages.newtype.HearingExerciseActivity;
import com.shushan.pages.newtype.SpeakingExerciseActivity;
import com.shushan.pages.newtype.StrangeWordsExerciseActivity;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.OffsetRecyclerDivider;
import com.shushan.ui.RefreshHeader;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.ControlUtil;
import com.shushan.util.DensityUtil;
import com.shushan.util.GlideImageLoader;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.web.AdvertWebActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ChildMainFragment
 * @Desciption: 孩子首页
 * @author: yichaohua
 * @date: 2018-08-09
 */
public class ChildMainFragment extends BaseHomeFragment implements XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, View.OnClickListener, VerificationCodeView.OnCodeFinishListener,
        RecommendLessonsAdapter.OnItemClickListener{

    private static final String TAG = "ChildMainFragment";

    private XRefreshView xRefreshView;
    private UnScrollGrideView scrollGrideView;
    private WhiteAppsAdapter whiteAppsAdapter;
    private TextView learnByChineseText;
    private TextView learnByMathText;
    private TextView learnByEnglishText;
    private LinearLayout changeLayout;
    private TextView whiteHintText;
    private Banner mBanner;
    private TextView tvRightGrade;
    private LinearLayout gradeLayout;
    private RecyclerView rvRecommendLessons;

    private List<LearnByDoBean> chineseLearnList;
    private List<LearnByDoBean> mathLearnList;
    private List<LearnByDoBean> englishLearnList;
    private List<BannerDataBean> bannerDataBeanList;
    private List<SubjectSyncExerciseBean> exerciseBeans;
    private int chineseIndex = 0;
    private int mathIndex = 0;
    private int englishIndex = 0;
    private LinearLayout llSyncExercise;
    private LinearLayout llStrangeWordsExercise;
    private LinearLayout llOralCalculateExercise;
    private LinearLayout llSpeakingExercise;
    private LinearLayout llEnglishWordsExercise;
    private LinearLayout llHearingExercise;
    private RelativeLayout rlChineseLearnByDo;
    private RelativeLayout rlMathLearnByDo;
    private RelativeLayout rlEnglishLearnByDo;
    private VerificationCodeView veriCodeView;
    public int score,time;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private Dialog noBookDialog;
    private Dialog changeToParentDialog;
    private FingerprintIdentify mFingerprintIdentify;
    private Dialog noVipDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        Log.i(TAG,"onCreateView()");

        View view = inflater.inflate(R.layout.child_main_fragment, null);
        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,getActivity())){
            view.findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        initView(view);

        //初始化广告栏
        initBanner();

        boolean isEyeOpen = SharedPreferencesUtils.getBooleanDate(Constants.PROJECT_EYE_SWITCH_SHAREPREFERS_KEY);
        if(isEyeOpen){
            int eyeInterval = SharedPreferencesUtils.getIntDate(Constants.PROJECT_EYE_INTERVAL_SHAREPREFERS_KEY);
            ControlUtil.setEyeProjectAlarm(getActivity(),eyeInterval);
        }

        xRefreshView.startRefresh();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        setAllowBack(false);

        if (shuShanApplication.isHomeFresh()){
            getData();
        }

        shuShanApplication.setHomeFresh(false);
    }

    private void initView(View view) {
        gradeLayout = view.findViewById(R.id.actionbar_right_grade_layout);
        gradeLayout.setOnClickListener(this);
        mBanner = view.findViewById(R.id.banner);
        whiteHintText = view.findViewById(R.id.child_main_white_hint_tv);
        changeLayout = view.findViewById(R.id.child_main_learnby_change_layout);
        changeLayout.setOnClickListener(this);
        scrollGrideView = view.findViewById(R.id.child_main_gv);
        scrollGrideView.setOnItemClickListener(this);
        whiteAppsAdapter = new WhiteAppsAdapter(getActivity());
        scrollGrideView.setAdapter(whiteAppsAdapter);
        xRefreshView = view.findViewById(R.id.child_main_refv);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setXRefreshViewListener(this);
        xRefreshView.setCustomHeaderView(new RefreshHeader(getActivity()));
        learnByChineseText = view.findViewById(R.id.child_main_learn_by_chinese_tv);
        learnByMathText = view.findViewById(R.id.child_main_learn_by_math_tv);
        learnByEnglishText = view.findViewById(R.id.child_main_learn_by_english_tv);
        llSyncExercise = view.findViewById(R.id.ll_sync_exercise);
        llSyncExercise.setOnClickListener(this);
        llStrangeWordsExercise = view.findViewById(R.id.ll_strange_words_exercise);
        llStrangeWordsExercise.setOnClickListener(this);
        llOralCalculateExercise = view.findViewById(R.id.ll_oral_calculate_exercise);
        llOralCalculateExercise.setOnClickListener(this);
        llSpeakingExercise = view.findViewById(R.id.ll_speaking_exercise);
        llSpeakingExercise.setOnClickListener(this);
        llEnglishWordsExercise = view.findViewById(R.id.ll_english_words_exercise);
        llEnglishWordsExercise.setOnClickListener(this);
        llHearingExercise = view.findViewById(R.id.ll_hearing_exercise);
        llHearingExercise.setOnClickListener(this);
        rlChineseLearnByDo = view.findViewById(R.id.rl_chinese_learn_by_do);
        rlChineseLearnByDo.setOnClickListener(this);
        rlMathLearnByDo = view.findViewById(R.id.rl_math_learn_by_do);
        rlMathLearnByDo.setOnClickListener(this);
        rlEnglishLearnByDo = view.findViewById(R.id.rl_english_learn_by_do);
        rlEnglishLearnByDo.setOnClickListener(this);
        tvRightGrade = view.findViewById(R.id.actionbar_right_grade_tv);
        tvRightGrade.setText(ToolUtils.getLevelTermText(shuShanApplication.getCurrentChildBean()));
        rvRecommendLessons = view.findViewById(R.id.rv_recommend_lessons);
        rvRecommendLessons.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvRecommendLessons.addItemDecoration(new OffsetRecyclerDivider(DensityUtil.dip2px(getActivity(),20f)));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mBanner.stopAutoPlay();

        if(noBookDialog != null){
            noBookDialog.dismiss();
        }

        if(changeToParentDialog != null){
            changeToParentDialog.dismiss();
        }

        if(noVipDialog != null){
            noVipDialog.dismiss();
        }

        if(mFingerprintIdentify != null){
            mFingerprintIdentify.cancelIdentify();
        }
    }

    private void initBanner(){
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR).setImageLoader(new GlideImageLoader());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(ToolUtils.isListEmpty(bannerDataBeanList)){
                    return;
                }else{
                    BannerDataBean dataBean = bannerDataBeanList.get(position);
                    bannerJump(dataBean);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_sync_exercise://同步练习
                if(isBookValide(Constants.TYPE_SYNC_EXERCISE,0)){
                    UmengEventUtil.onEvent(shuShanApplication,"sync_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(SyncExerciseActivity.class);
                }
                break;
            case R.id.ll_strange_words_exercise://生字练习
                if(isBookValide(Constants.TYPE_STRANGE_WORDS_EXERCISE,Constants.SUBJECT_CHINESE_ID)){
                    UmengEventUtil.onEvent(shuShanApplication,"words_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(StrangeWordsExerciseActivity.class);
                }
                break;
            case R.id.ll_oral_calculate_exercise://口算练习
                if(isBookValide(Constants.TYPE_ORAL_CALCULATE_EXERCISE,Constants.SUBJECT_MACH_ID)){
                    UmengEventUtil.onEvent(shuShanApplication,"oral_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(OralCalculateExerciseActivity.class);
                }
                break;
            case R.id.ll_speaking_exercise://口语练习
                if(isBookValide(Constants.TYPE_SPEAKING_EXERCISE,Constants.SUBJECT_ENGLISH_ID)){
                    UmengEventUtil.onEvent(shuShanApplication,"speaking_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(SpeakingExerciseActivity.class);
                }
                break;
            case R.id.ll_english_words_exercise://单词练习
                if(isBookValide(Constants.TYPE_ENGLISH_WORDS_EXERCISE,Constants.SUBJECT_ENGLISH_ID)){
                    UmengEventUtil.onEvent(shuShanApplication,"english_words_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(EnglishWordsExerciseActivity.class);
                }
                break;
            case R.id.ll_hearing_exercise://听力练习
                if(isBookValide(Constants.TYPE_HEARING_EXERCISE,Constants.SUBJECT_ENGLISH_ID)){
                    UmengEventUtil.onEvent(shuShanApplication,"hearing_exercise_click_id");
                    shuShanApplication.setHomeFresh(true);
                    startActivity(HearingExerciseActivity.class);
                }
                break;
            case R.id.rl_chinese_learn_by_do://语文边学边练
                gotoLearByDo(Constants.SUBJECT_CHINESE_ID);
                break;
            case R.id.rl_math_learn_by_do://数学边学边练
                gotoLearByDo(Constants.SUBJECT_MACH_ID);
                break;
            case R.id.rl_english_learn_by_do://英语边学边练
                gotoLearByDo(Constants.SUBJECT_ENGLISH_ID);
                break;
            case R.id.child_main_learnby_change_layout:
                setLearnByAdd();
                break;
            case R.id.actionbar_right_grade_layout:
                showToParentDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(int position,int practiceType) {
        Log.i(TAG,"practiceType=" + practiceType);
        SubjectSyncExerciseBean subjectSyncExerciseBean = null;
        if(exerciseBeans != null){
            subjectSyncExerciseBean = exerciseBeans.get(position);
        }

        exerciseBeans.get(position);
        if(!shuShanApplication.isSectVip(practiceType) && subjectSyncExerciseBean != null && subjectSyncExerciseBean.state == 1) {
            showNoVipDialog(practiceType,-1);
            return;
        }

        shuShanApplication.setHomeFresh(true);
        if(practiceType < 13) {
            setAllowBack(true);
            Intent intent = new Intent(getActivity(),MixedExamActivity.class);
            intent.putExtra("examType", practiceType);
            startActivity(intent);
        }else{
            startActivity(OralCalculateExamActivity.class);
        }
    }

    private void gotoLearByDo(int subject) {
        List<LearnByDoBean> learnList = null;
        Intent intent = new Intent(getActivity(),NewStudyWithExerciseActivity.class);
        switch (subject){
            case Constants.SUBJECT_CHINESE_ID:
                learnList = chineseLearnList;
                intent.putExtra("position",chineseIndex);
                break;
            case Constants.SUBJECT_MACH_ID:
                learnList = mathLearnList;
                intent.putExtra("position",mathIndex);
                break;
            case Constants.SUBJECT_ENGLISH_ID:
                learnList = englishLearnList;
                intent.putExtra("position",englishIndex);
                break;
            default:
                break;
        }

        ChildBookDao childBookDao = new ChildBookDao(getActivity());
        if(!childBookDao.containSubject(subject)) {
            showNoBookDialog(subject);
            return ;
        }

        if(ToolUtils.isListEmpty(learnList)){
            if(subject == Constants.SUBJECT_CHINESE_ID){
                showToast("暂只支持人教版");
            }else if(subject == Constants.SUBJECT_MACH_ID){
                showToast("暂只支持人教新版");
            }else if(subject == Constants.SUBJECT_ENGLISH_ID){
                showToast("暂只支持人教PEP版");
            }else {
                showToast("无数据");
            }
            return;
        }

        if (isBookValide(Constants.TYPE_LEARN_BY_DO,subject)){
            Session.getSession().put("learnByDoBeanList",learnList);

            intent.putExtra("subjectId",subject);
            intent.putExtra("score",score);
            intent.putExtra("time",time);
            startActivityAllow(intent);
        }
    }

    private void startLearByDo(int subject) {
        List<LearnByDoBean> learnList = null;
        Intent intent = new Intent(getActivity(),NewStudyWithExerciseActivity.class);
        switch (subject){
            case Constants.SUBJECT_CHINESE_ID:
                learnList = chineseLearnList;
                intent.putExtra("position",chineseIndex);
                break;
            case Constants.SUBJECT_MACH_ID:
                learnList = mathLearnList;
                intent.putExtra("position",mathIndex);
                break;
            case Constants.SUBJECT_ENGLISH_ID:
                learnList = englishLearnList;
                intent.putExtra("position",englishIndex);
                break;
            default:
                break;
        }

        Session.getSession().put("learnByDoBeanList",learnList);

        intent.putExtra("subjectId",subject);
        intent.putExtra("score",score);
        intent.putExtra("time",time);
        startActivityAllow(intent);
    }

    @Override
    public void onRefresh() {
        new GetAppListTask().execute();
        getData();
    }

    @Override
    public void onRefresh(boolean isPullDown) {

    }

    @Override
    public void onLoadMore(boolean isSilence) {

    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(!SystemUtils.checkUsagePermission(getActivity())){
            showNoUsageDialog();
            return;
        }

        List<AppInfo> appInfoList = whiteAppsAdapter.getAppInfoList();
        AppInfo appInfo = appInfoList.get(position);

        super.setAllowBack(true);
        SystemUtils.startApp(getActivity(),appInfo.getPackageName());

        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if (isChildControl){
            Intent intent = new Intent(getActivity(),ForegroundRTAService.class);
            intent.putExtra("paperId",-1);
            intent.putExtra("allowPackName",appInfo.getPackageName());
            intent.putExtra("allowAppLabel",appInfo.getLabel());
            intent.putExtra("isWhitePlay",true);

            getActivity().startService(intent);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            if(changeToParentDialog != null){
                changeToParentDialog.dismiss();
            }

            startActivity(ParentSettingActivity.class);
        }else {
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    @Override
    public void onFragmentChecked() {
        Log.i(TAG,"onFragmentChecked()");
        tvRightGrade.setText(ToolUtils.getLevelTermText(shuShanApplication.getCurrentChildBean()));
        getData();
    }

    @Override
    public void onFragmentHided() {

    }

    private class GetAppListTask extends AsyncTask<Void,Void,List<AppInfo>> {

        @Override
        protected List<AppInfo> doInBackground(Void... voids) {
            List<AppInfo> appInfoList = SystemUtils.getUsePackages(true,getActivity());

            return appInfoList;
        }

        @Override
        protected void onPostExecute(List<AppInfo> appInfoList) {
            if(ToolUtils.isListEmpty(appInfoList)){
                whiteHintText.setVisibility(View.VISIBLE);
                return;
            }else {
                whiteHintText.setVisibility(View.GONE);
            }

            whiteAppsAdapter.setAppInfoList(appInfoList);
            whiteAppsAdapter.notifyDataSetChanged();
        }
    }

    private void getData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.GET_CHILD_INDEX);
        urlParse.putValue("child_id", childId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<IndexBean>() {
                    @Override
                    protected void onCommon() {
                        xRefreshView.stopRefresh();
                    }

                    @Override
                    protected void onSuccess(IndexBean indexBean) {
                        if(indexBean != null){
                            score = indexBean.score;
                            time = indexBean.time;
                            bannerDataBeanList = indexBean.getBannerDataBeanList();
                            chineseLearnList = indexBean.getChineseLearnList();
                            mathLearnList = indexBean.getMathLearnList();
                            englishLearnList = indexBean.getEnglishLearnList();

                            chineseIndex = 0;
                            mathIndex = 0;
                            englishIndex = 0;
                            setLearnBy();

                            setBanner();

                            exerciseBeans = indexBean.getSubjectBeans();
                            RecommendLessonsAdapter lessonsAdapter = new RecommendLessonsAdapter(getActivity(),exerciseBeans);
                            lessonsAdapter.setOnItemClickListener(ChildMainFragment.this);
                            rvRecommendLessons.setAdapter(lessonsAdapter);
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private boolean isBookContain(int subjectId){
        ChildBookDao childBookDao = new ChildBookDao(getActivity());
        if(!childBookDao.containSubject(subjectId)) {
            return false;
        }
        return true;
    }

    private void setBanner(){
        if(ToolUtils.isListEmpty(bannerDataBeanList)){
            Log.d(TAG,"banner数据为空");
            return;
        }
        List<String> images = new ArrayList<String>();
        for(BannerDataBean bean : bannerDataBeanList){
            String loadUrl;
            if (ImageUtils.isAbsoluteUrl(bean.pic)) {
                loadUrl = bean.pic;
            } else {
                loadUrl = BuildConfig.imgBaseUrl + bean.pic;
            }
            images.add(loadUrl);
        }
        mBanner.setImages(images).start();
    }

    //根据type跳转不同界面
    private void bannerJump(BannerDataBean dataBean){
        switch (dataBean.type){
            case 0://跳转H5
                Intent intent2 = new Intent(getActivity(), AdvertWebActivity.class);
                intent2.putExtra("title",dataBean.name);
                intent2.putExtra("url",dataBean.url);
                startActivityAllow(intent2);
                break;
            case 1://跳转APP页面
                if(dataBean.url.equals("0")){
                    startActivity(InviteForFreeUseActivity.class);
                }else if(!TextUtils.isEmpty(dataBean.android_name)){
                    try {
                        Intent intent1 = new Intent();
                        intent1.setClassName(getContext(),dataBean.android_name);
                        startActivityAllow(intent1);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case 2://跳转视频页面
                Intent intent = new Intent(getActivity(),SpecialTopicVideoActivity.class);
                intent.putExtra("isOnlyPlay",true);
                intent.putExtra("video_title",dataBean.name);
                intent.putExtra("video_url",dataBean.url);
                startActivityAllow(intent);
                break;
            default:
                break;
        }
    }

    private void setLearnByAdd() {
        chineseIndex++;
        mathIndex++;
        englishIndex++;
        setLearnBy();
    }

    private void setLearnBy() {
        if(!ToolUtils.isListEmpty(chineseLearnList)){
            if(chineseIndex > (chineseLearnList.size()-1)){
                chineseIndex = chineseIndex % chineseLearnList.size();
            }
            LearnByDoBean learnByDoBean = chineseLearnList.get(chineseIndex);
            learnByChineseText.setText(learnByDoBean.video_title);
        }else {
            learnByChineseText.setText("");
        }

        if(!ToolUtils.isListEmpty(mathLearnList)){
            if(mathIndex > (mathLearnList.size()-1)){
                mathIndex = mathIndex % mathLearnList.size();
            }
            LearnByDoBean learnByDoBean = mathLearnList.get(mathIndex);
            learnByMathText.setText(learnByDoBean.video_title);
        }else {
            learnByMathText.setText("");
        }

        if(!ToolUtils.isListEmpty(englishLearnList)){
            if(englishIndex > (englishLearnList.size()-1)){
                englishIndex = englishIndex % englishLearnList.size();
            }
            LearnByDoBean learnByDoBean = englishLearnList.get(englishIndex);
            learnByEnglishText.setText(learnByDoBean.video_title);
        }else {
            learnByEnglishText.setText("");
        }
    }

    private boolean isBookValide(int exerciseType,int subjectId) {
        ChildBookDao childBookDao = new ChildBookDao(getActivity());
        if(!childBookDao.containSubject(subjectId)) {
            showNoBookDialog(subjectId);

            return false;
        }

        if(!shuShanApplication.isSectVip(exerciseType)) {
            showNoVipDialog(exerciseType,subjectId);
            return false;
        }

        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + shuShanApplication.getCurrentChildId());
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(isChildControl && gameTime > 0){
            showExistTimeDialog(exerciseType,subjectId);
            return false;
        }

        return true;
    }

    private void showExistTimeDialog(final int exerciseType,final int subjectId) {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您还有手机娱乐时间，是否去游戏？")
                .setNegativeButton("去学习", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        gotoExercise(exerciseType,subjectId);
                    }
                })
                .setPositiveButton("去娱乐", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        ControlUtil.gotoGamesFloat(getActivity());
                    }
                })
                .create().show();
    }

    private void gotoExercise(int exerciseType,int subjectId) {
        switch (exerciseType){
            case Constants.TYPE_SYNC_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"sync_exercise_click_id");
                startActivity(SyncExerciseActivity.class);
                break;
            case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                UmengEventUtil.onEvent(shuShanApplication,"words_exercise_click_id");
                startActivity(StrangeWordsExerciseActivity.class);
                break;
            case Constants.TYPE_ORAL_CALCULATE_EXERCISE://口算练习
                UmengEventUtil.onEvent(shuShanApplication,"oral_exercise_click_id");
                startActivity(OralCalculateExerciseActivity.class);
                break;
            case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                UmengEventUtil.onEvent(shuShanApplication,"speaking_exercise_click_id");
                startActivity(SpeakingExerciseActivity.class);
                break;
            case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                UmengEventUtil.onEvent(shuShanApplication,"english_words_exercise_click_id");
                startActivity(EnglishWordsExerciseActivity.class);
                break;
            case Constants.TYPE_HEARING_EXERCISE://听力练习
                UmengEventUtil.onEvent(shuShanApplication,"hearing_exercise_click_id");
                startActivity(HearingExerciseActivity.class);
                break;
            case Constants.TYPE_LEARN_BY_DO:
                startLearByDo(subjectId);
                break;
            default:
                break;
        }
    }

    private void showNoBookDialog(int subjectId) {
        noBookDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
        noBookDialog.setCanceledOnTouchOutside(true);
        noBookDialog.setContentView(R.layout.no_book_dialog);

        TextView textView = noBookDialog.findViewById(R.id.no_book_tv);
        if(subjectId == Constants.SUBJECT_CHINESE_ID){
            textView.setText("请添加语文课本！");
        }else if(subjectId == Constants.SUBJECT_MACH_ID){
            textView.setText("请添加数学课本！");
        }else if(subjectId == Constants.SUBJECT_ENGLISH_ID){
            textView.setText("请添加英语课本！");
        }

        Button addButton = noBookDialog.findViewById(R.id.no_book_postitve_btn);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noBookDialog.dismiss();
                showToParentDialog();
            }
        });

        Button cancelButton = noBookDialog.findViewById(R.id.no_book_cancel_btn);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noBookDialog.dismiss();

            }
        });


        if(!noBookDialog.isShowing()){
            noBookDialog.show();
        }
    }

    private void showToParentDialog() {
        if(changeToParentDialog == null){
            changeToParentDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
            changeToParentDialog.setContentView(R.layout.change_to_parent_dialog);
            changeToParentDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            veriCodeView = changeToParentDialog.findViewById(R.id.verification_code_view);
            veriCodeView.setOnCodeFinishListener(this);
            Button coloseButton = changeToParentDialog.findViewById(R.id.btn_cancel);
            coloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeToParentDialog.dismiss();
                    if(mFingerprintIdentify != null){
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            changeToParentDialog.setCancelable(false);
        }

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        ImageView parentImg = changeToParentDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = changeToParentDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = changeToParentDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView)changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码去设置");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    startActivity(ParentSettingActivity.class);
                    changeToParentDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            ((TextView)changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码去设置");
        }

        if(veriCodeView != null){
            veriCodeView.clear();
        }

        if(!changeToParentDialog.isShowing()){
            changeToParentDialog.show();
        }
    }

    private void gotoExerciese(int exerciseType,int subjectId) {
        Log.i(TAG,"exerciseType=" + exerciseType);

        switch (exerciseType){
            case Constants.TYPE_SYNC_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"sync_exercise_click_id");
                startActivity(SyncExerciseActivity.class);
                break;
            case Constants.TYPE_STRANGE_WORDS_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"words_exercise_click_id");
                startActivity(StrangeWordsExerciseActivity.class);
                break;
            case Constants.TYPE_ORAL_CALCULATE_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"oral_exercise_click_id");
                startActivity(OralCalculateExerciseActivity.class);
                break;
            case Constants.TYPE_SPEAKING_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"speaking_exercise_click_id");
                startActivity(SpeakingExerciseActivity.class);
                break;
            case Constants.TYPE_ENGLISH_WORDS_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"english_words_exercise_click_id");
                startActivity(EnglishWordsExerciseActivity.class);
                break;
            case Constants.TYPE_HEARING_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication,"hearing_exercise_click_id");
                startActivity(HearingExerciseActivity.class);
                break;
            case Constants.TYPE_LEARN_BY_DO:
                List<LearnByDoBean> learnList = null;
                Intent intent = new Intent(getActivity(),NewStudyWithExerciseActivity.class);

                if(subjectId == Constants.SUBJECT_CHINESE_ID){
                    learnList = chineseLearnList;
                    intent.putExtra("position",chineseIndex);
                }else if(subjectId == Constants.SUBJECT_MACH_ID){
                    learnList = mathLearnList;
                    intent.putExtra("position",mathIndex);
                }else if(subjectId == Constants.SUBJECT_ENGLISH_ID){
                    learnList = englishLearnList;
                    intent.putExtra("position",englishIndex);
                }
                Session.getSession().put("learnByDoBeanList",learnList);

                intent.putExtra("subjectId",subjectId);
                intent.putExtra("score",score);
                intent.putExtra("time",time);
                startActivityAllow(intent);
                break;
            default:
                break;
        }
    }

    private void showNoVipDialog(final int exerciseType,final int subjectId) {
        noVipDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
        noVipDialog.setCanceledOnTouchOutside(true);
        noVipDialog.setContentView(R.layout.no_sect_vip_dialog);

        Button tryoutButton = noVipDialog.findViewById(R.id.no_vip_tryout_btn);
        if(subjectId < 0){
            tryoutButton.setVisibility(View.GONE);
        }
        tryoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();
                gotoExerciese(exerciseType,subjectId);
            }
        });

        Button openSectBtn = noVipDialog.findViewById(R.id.no_vip_open_sect_btn);
        openSectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();

                Intent intent = new Intent(getActivity(),OpenSectVipActivity.class);
                intent.putExtra("exerciseType",exerciseType);
                startActivityAllow(intent);
            }
        });

        Button openAllBtn = noVipDialog.findViewById(R.id.no_vip_open_all_btn);
        openAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();
                startActivity(OpenVipSpendActivity.class);
            }
        });


        if(!noVipDialog.isShowing()){
            noVipDialog.show();
        }
    }
}
